import {_decorator, Component, Node, resources, TextAsset, Label} from 'cc';

const {ccclass, property} = _decorator;

@ccclass('Text')
export class Text extends Component {
    @property(Label)
    labelTitle: Label = null
    @property(Label)
    labelContext: Label = null

    title: string = null
    context: string = null

    // TextAsset 表示文本资源
    onLoad() {
        const that = this;
        resources.load("滕王阁序", function (err, data: TextAsset) {
            if (err) {
                console.error(err);
                return
            }
            //文本标题
            that.title = data.name
            //文本内容
            that.context = data.text
        })
    }

    start() {
        this.labelTitle.string = this.title
        this.labelContext.string = this.textStyle(this.context)

    }

    update(deltaTime: number) {

    }

    textStyle(text: string): string {
        let str: string = ""
        const maxSize = 40
        let length = text.length;
        // Math.cell 向上取整
        let count = Math.ceil(length / maxSize)//文本行数

        for (let i = 0; i < count; ++i) {
            let startIndex: number = i * 40
            let endIndex: number = startIndex + maxSize
            if (startIndex + maxSize > length) endIndex = length

            str += text.substring(startIndex, endIndex)+"\n"
        }
        return str
    }
}


